package com.kayak.kboot.web.filter;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.kayak.kboot.web.sys.RequestSupport;
import com.kayak.kboot.web.sys.SysBeans;

/**
 * @author somebody
 *
 */

@WebFilter
public class LocalRequestFilter implements Filter {
	private Logger log = LoggerFactory.getLogger(LocalRequestFilter.class);

	private String encoding;

	private boolean forceEncoding;
	private String errorPage;

	public void init(FilterConfig config) throws ServletException {
		SysBeans.setCurrentApplicationContext(WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()));
		encoding = config.getInitParameter("encoding");
		encoding = encoding == null ? "UTF-8" : encoding;
		if ("false".equals(config.getInitParameter("forceEncoding"))) {
			forceEncoding = false;
		} else {
			forceEncoding = true;
		}
		errorPage = config.getInitParameter("error-page");
	}

	public void destroy() {
		SysBeans.setCurrentApplicationContext(null);
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request.getCharacterEncoding() == null) {
			request.setCharacterEncoding(encoding);
			if (forceEncoding) {
				response.setCharacterEncoding(encoding);
			}
		}
		String uri = ((HttpServletRequest) request).getRequestURI();
		String mdc = uri.substring(uri.lastIndexOf("/") + 1, uri.length()).replace(".", "_");
		log.info("Ipaddr:[{}], requestURI:[{}], contentType:[{}], mdc:[{}]", getIpAddr((HttpServletRequest) request),
				uri, request.getContentType(), mdc);
		MDC.put("servlet_path", mdc);
		RequestSupport.setLocalRequest((HttpServletRequest) request);
		RequestSupport.setRequestParams();
		chain.doFilter(request, response);
	}

	/**
	 * 获取当前网络ip
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	public String getErrorPage() {
		return errorPage;
	}

	public void setErrorPage(String errorPage) {
		this.errorPage = errorPage;
	}

}
